<?php
class News_model_news extends Model {
    private $table_news = 'news';
    private $table_node = 'n_node';
    
    public function get_content($node_id) {
        $node_id = (int) $node_id;
        if ($node_id <= 0) tos_die();
        
        return $this->db->select_row(
            $this->table_news,
            array('content', 'expired', 'published'),
            array('node_id' => $node_id),
            array('node_id' => DB_DATA_INT)
        );
    }
    
    public function edit_content($node_id, $data) {
        $node_id = (int) $node_id;
        if ($node_id <= 0) tos_die();
        
        $db = $this->db;
        $table = $this->table_news;
        
        $content = isset($data['content']) ? trim($data['content']) : false;
        $expired = isset($data['expired']) ? (int) $data['expired'] : false;
        $published = isset($data['published']) ? (int) $data['published'] : time();
        if ($content) $db_data['content'] = $content;
        if ($expired) $db_data['expired'] = $expired;
        if ($published) $db_data['published'] = $published;
        $db_data['node_id'] = $node_id;
        
        
        $row = $db->select_row(
            $table,
            array('id'),
            array('node_id' => $node_id),
            array('node_id' => DB_DATA_INT)
        );
        
        if ($row) {
            $id = (int) $row['id'];
            if ($id <= 0) tos_die();
            $db->update(
                $table,
                $db_data,
                array('id' => $id),
                array('expired' => DB_DATA_INT, 'published' => DB_DATA_INT)
            );
        } else {
            if ( ! $content) tos_die();
            $id = $db->insert(
                $table,
                $db_data,
                array('expired' => DB_DATA_INT, 'published' => DB_DATA_INT)
            );
        }
        return $id;
    }
    public function remove_content($node_id) {
        $node_id = (int) $node_id;
        if ($node_id <= 0) tos_die();
        
        return $this->db->delete($this->table_news, array('node_id' => $node_id));
    }
    
    
    public function get_list($offset = 0, $limit = 11) {
        $offset = (int) $offset;
        $limit = (int) $limit;
        $sql = "SELECT `news`.`published`, `node`.* FROM `{$this->table_news}` `news` " .
            "INNER JOIN `{$this->table_node}` `node` ON `news`.`node_id`=`node`.`id` " .
            "ORDER BY `news`.`published` DESC LIMIT $offset,$limit";
        return $this->db->rows($sql);
    }
    
    public function get_count() {
        $sql = "SELECT count(*) count FROM `{$this->table_news}`";
        $row = $this->db->row($sql);
        return (int) $row['count'];
    }
}
?>